package leetcode;

import leetcode.vo.ListNode;

public class MergeTwoSortedLists {

    public static void main(String[] args) {

        ListNode n1 = new ListNode();
        n1.val = 2;
        ListNode n2 = new ListNode();
        n2.val = 3;
        ListNode n3 = new ListNode();
        n3.val = 5;
        n1.next = n2;
        n2.next = n3;

        ListNode n11 = new ListNode();
        n11.val = 3;
        ListNode n12 = new ListNode();
        n12.val = 6;
        ListNode n13 = new ListNode();
        n13.val = 9;
        n11.next = n12;
        n12.next = n13;

        MergeTwoSortedLists m = new MergeTwoSortedLists();

        ListNode listNode = m.mergeTwoLists(n1, n11);
        System.out.println(listNode);

    }

    public ListNode mergeTwoLists(ListNode l1, ListNode l2) {
        ListNode l = new ListNode();
        ListNode prev = l;
        while(l1 != null || l2 != null){
            if(l1 == null){
                prev.next = l2;
                break;
            }else if(l2 == null){
                prev.next = l1;
                break;
            }else if(l1.val <= l2.val){
                prev.next = l1;
                l1 = l1.next;
            }else{
                prev.next = l2;
                l2 = l2.next;
            }
            prev = prev.next;
        }
        return l.next;
    }

}
